<!-- 仪器管理页 -->
<template>
  <div style="height:6vh;background-color:#fff;padding: 10px 20px;">
    <span style="line-height: 60px;font-size: 20px;">仪器管理</span>
    <el-button type="primary" style="float:right;margin-top:10px;"
               @click="beforeAddUser">新增仪器</el-button>
  </div>
  <!-- 保存仪器数据弹窗 -->
  <el-dialog
      :title="dialogTitle"
      style="width: 1000px;padding:40px;" v-model="dialogVisible" :before-close="handleClose">
    <el-form label-width="80px" label-position="top">
      <el-row :gutter="10">
        <el-col :span="12">
          <el-form-item label="项目名称">
            <el-input placeholder="请输入项目名"
                      v-model="saveEquipmentForm.projectName"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="仪器名">
            <el-input placeholder="请输入仪器号" v-model="saveEquipmentForm.instrumentName"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="10">
        <el-col :span="12">
          <el-form-item label="仪器类型">
            <el-select placeholder="请选择类型" v-model="saveEquipmentForm.instrumentType">
              <el-option label="试验仪器" value="试验仪器"></el-option>
              <el-option label="测量仪器" value="测量仪器"></el-option>
              <el-option label="场站设备" value="场站设备"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="使用情况">
            <el-select placeholder="请选择使用情况" v-model="saveEquipmentForm.usageStatus">
              <el-option label="正常" value="正常"></el-option>
              <el-option label="停用" value="停用"></el-option>
              <el-option label="调出" value="调出"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="10">
        <el-col :span="6">
          <el-form-item label="标定开始时间">
            <el-date-picker type="date" format="YYYY-MM-DD" value-format="YYYY-MM-DD" v-model="saveEquipmentForm.calibrationDate"
                            @change="validateDate"/>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="标定截止时间">
            <el-date-picker type="date" format="YYYY-MM-DD" value-format="YYYY-MM-DD" v-model="saveEquipmentForm.expirationDate"
                            @change="validateDate"/>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="是否鉴定">
            <el-radio-group v-model="saveEquipmentForm.isCertified">
              <el-radio border label="是" value="1" style="margin:0;"></el-radio>
              <el-radio border label="否" value="0"></el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="3">
          <el-form-item label="添加人" style="width: 100px;">
            <el-input placeholder="请输入添加人" :value="user.username" readonly></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item label="标定证书" v-if="isAddUserMode">
            <el-upload
                v-model:file-list="fileList"
                v-model:action="actionUrl"
                name="file"
                limit="1"
                list-type="picture-card"
                :on-preview="handlePictureCardPreview"
                :on-remove="handleRemove"
            >
              <el-icon><Plus /></el-icon>
            </el-upload>
            <el-dialog v-model="dialogImgVisible">
              <img w-full :src="dialogImageUrl"/>
            </el-dialog>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" @click="saveEquipment">保存</el-button>
    </template>
  </el-dialog>
  <!-- 仪器搜索卡片 -->
  <el-card style="margin: 20px;height: 70px;">
    <el-form :inline="true">
      <el-form-item label="仪器搜索" style="width: 270px;">
        <el-input placeholder="请输入仪器名"
                  v-model="searchEquipmentForm.instrumentName" @keydown.enter="loadEquipment"></el-input>
      </el-form-item>
      <el-form-item label="使用情况" style="width: 290px;">
        <el-select placeholder="请选择试验状态"
                   v-model="searchEquipmentForm.usageStatus" @change="loadEquipment">
          <el-option label="正常" value="0"></el-option>
          <el-option label="使用" value="1"></el-option>
          <el-option label="调出" value="2"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button @click="resetSearch">重置</el-button>
        <el-button type="primary" @click="loadEquipment">搜索</el-button>
      </el-form-item>
    </el-form>
  </el-card>
  <!-- 仪器数据表格卡片 -->
  <el-card style="margin:20px;">
    <el-table :data="equipmentArr">
      <el-table-column label="序号" type="index" width="80" align="center"></el-table-column>
      <el-table-column label="项目名称" prop="projectName" align="center"></el-table-column>
      <el-table-column label="仪器名称" prop="instrumentName" align="center"></el-table-column>
      <el-table-column label="仪器类型" prop="instrumentType" align="center"></el-table-column>
      <el-table-column label="使用情况" prop="usageStatus" align="center" :formatter="itemFormatter"></el-table-column>
      <el-table-column label="是否鉴定" prop="isCertified" align="center">
          <template #default="scope">
            <el-switch active-value="1" inactive-value="0" v-model="scope.row.isCertified"
                       @change="updateStatus(scope.row.serialNumber,scope.row.isCertified)"></el-switch>
          </template>
      </el-table-column>
      <el-table-column label="标定时间" prop="calibrationDate" align="center"></el-table-column>
      <el-table-column label="截止时间" prop="expirationDate" align="center"></el-table-column>
      <el-table-column label="添加人" prop="addedBy" align="center"></el-table-column>
      <el-table-column label="添加时间" prop="addedTime" align="center"></el-table-column>
      <el-table-column label="操作" align="center">
        <template #default="scope">
          <el-button type="primary" link
                     @click="editEquipment(scope.row.serialNumber)">编辑</el-button>
          <el-button type="primary" link
                     @click="deleteEquipment(scope.row.serialNumber)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div style="margin:30px;float: right;">
      <!--layout="total(总数), sizes(每页总数), prev(上一页), pager(当前页), next(下一页), jumper(跳转页)"
       :pager-count="4" 表示显示4个页码
       :page-sizes="[5, 10, 15, 20]" 表示一共有几个"每页显示多少条"选项
       current-page当前页码 page-size当前页码的条数 total总条数 这三个变量需要和实际数据双向绑定
       :total="400" 表示总条数，需要双向绑定
       @size-change="handleSizeChange" 表示每页显示多少条改变时触发的事件
       @current-change="handleCurrentChange" 表示当前页码改变时触发的事件 -->
      <el-pagination
          layout="total, sizes, prev, pager, next, jumper"
          :page-sizes="[5, 10]"
          :pager-count="4"
          v-model:current-page="currentPage"
          v-model:page-size="currentSize"
          v-model:total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      />
    </div>
  </el-card>
<!--  <hr>
  <h4>显示后端返回的图片路径: <span>{{tempImgUrl}}</span></h4>
  <img :src="BASE_URL+tempImgUrl" alt="">-->
</template>

<script setup>
import {onMounted, ref} from "vue";
import axios from "axios";
import qs from "qs";
import {ElMessage} from "element-plus";
const validateDate=()=>{
  const startTime=saveEquipmentForm.value.calibrationDate;
  const endTime=saveEquipmentForm.value.expirationDate;
  if(endTime&&startTime&&new Date(endTime)<=new Date(startTime)){
    ElMessage.error('截止时间不能早于开始时间');
    saveEquipmentForm.value.endTime='';
  }
}
//定义变量用来保存图片提交的后端接口地址
const actionUrl = ref(BASE_URL+'/v1/file/upload');
//定义一个变量用来保存上传的图片路径
const tempImgUrl = ref('');
//图片预览方法
const handlePictureCardPreview = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url
  dialogImgVisible.value = true
  //打印上传的图片对象
  console.log(fileList.value);
  console.log(fileList.value[0]);
  //获取上传的图片路径
  tempImgUrl.value = fileList.value[0].response.data;
}
//定义变量用来控制弹窗是否出现
const dialogVisible = ref(false);
//定义用来维护可选直属领导的领导人数组
const leaderOptions = ref([
  // {username: '张三', id: 201},
  // {username: '李四', id: 202}
]);
//定义对象用来保存仪器表单数据
const saveEquipmentForm = ref({
  projectName: '',
  instrumentName: '',
  instrumentType: '',
  usageStatus: '',
  isCertified: '',
  calibrationDate: '',
  expirationDate: ''
});
//定义变量保存分页器的当前页数
const currentPage = ref(1);
//定义变量保存分页器的每页显示多少条
const currentSize = ref(5);
//定义变量保存数据总条目数
const total = ref(100);
//修改每页显示多少条，触发此函数
const user=ref(getUser());
//定义数组用来保存上传的图片对象
const fileList = ref([]);
//每次点击"新增仪器"按钮时调用的方法
const beforeAddUser = ()=>{
  dialogTitle.value = '新增仪器';
  dialogVisible.value = true;
  isAddUserMode.value = true;
}
//定义保存仪器的方法
const saveEquipment = () => {
  if(fileList.value.length==0){
    ElMessage.warning('请上传驾照图片!');
    return;
  }
  saveEquipmentForm.value.addedBy=user.value.username;
  saveEquipmentForm.value.imgUrl=fileList.value[0].response.data;
  let data = qs.stringify(saveEquipmentForm.value);
  console.log(data);
  axios.post(BASE_URL+'/experiment/save',data)
      .then((response)=>{
        if (response.data.code == 2000) {
          ElMessage.success('保存成功!');
          dialogVisible.value = false;//关闭弹窗
          saveEquipmentForm.value = {};//清空表单
          fileList.value=[];
          loadEquipment();//新增成功后,需要重新加载数据!
        } else {
          ElMessage.error('保存失败!');
        }
      })
}
const updateStatus = (serialNumber,isCertified) => {
  axios.post(BASE_URL+'/experiment/update/'+serialNumber+"/"+isCertified)
      .then((response)=>{
        if(response.data.code==2000){
          ElMessage.success('状态修改成功!')
        }else {
          ElMessage.error(response.data.msg);
        }
      })
}
//定义处理弹窗关闭的方法
const handleClose = () => {
  if(confirm('您是否要关闭本弹窗?')){
    fileList.value=[];
    saveEquipmentForm.value = {};
    dialogVisible.value = false;
  }
}
//定义对象用来保存仪器搜索条件
const searchEquipmentForm = ref({instrumentName: '', usageStatus: ''});
//定义数组用来保存仪器表格数据
const equipmentArr = ref([]);
//定义加载仪器数据的方法
const loadEquipment = ()=>{
  searchEquipmentForm.value.pageSize = currentSize.value;
  searchEquipmentForm.value.pageNum = currentPage.value;
  console.log(searchEquipmentForm.value);
  let data = qs.stringify(searchEquipmentForm.value);
  console.log(data);
  axios.get(BASE_URL+'/experiment/select?'+data)
      .then((response)=>{
        if (response.data.code == 2000) {
/*          equipmentArr.value = response.data.data;*/
          console.log(equipmentArr.value);
          //dictArr.value = response.data.data;
          equipmentArr.value = response.data.data.list;//所以要多加一层list
          total.value = response.data.data.total;//设置总条目数
        }else{
          ElMessage.error(response.data.msg);
        }
      })
}
const handleSizeChange = (val) => {
  console.log('每页展示' + val + '条数据');
  currentSize.value = val;
  loadEquipment();
}
//修改当前页码，触发此函数
const handleCurrentChange = (val) => {
  console.log('当前的页数为：' + val);
  currentPage.value = val;
  loadEquipment();
}
//一进到页面立即加载所有仪器数据
onMounted(()=>{
  loadEquipment();
})
//定义重置搜索的方法
const resetSearch = () => {
  searchEquipmentForm.value = {};
  loadEquipment();
}
const itemFormatter = (row,column,cellValue,index) => {
  if(!equipmentArr.value){
    return cellValue;
  }
  if(cellValue==0){
    cellValue='正常';
  }else if(cellValue==1){
    cellValue='停用';
  }else if(cellValue==2){
    cellValue='调出';
  }
  return cellValue;
}
//定义变量来维护弹窗标题
const dialogTitle = ref('新增仪器');
//定义编辑仪器的方法
const editEquipment = (serialNumber)=>{
  isAddUserMode.value = false;
  dialogTitle.value = '编辑仪器';
  dialogVisible.value = true;
  console.log('仪器序号是'+serialNumber);
  axios.get(BASE_URL+'/experiment/select?serialNumber='+serialNumber).then((response)=>{
    if (response.data.code == 2000) {
      saveEquipmentForm.value = response.data.data.list[0];
      console.log(saveEquipmentForm.value);
    }else{
      ElMessage.error(response.data.msg);
    }
  })
}
//定义删仪器的方法
const deleteEquipment = (serialNumber)=>{
  if(confirm('您确认要删除此仪器吗?')){
    axios.post(BASE_URL+'/experiment/delete/'+serialNumber).then((response)=>{
      if(response.data.code == 2000){
        ElMessage.success('删除成功!');
        loadEquipment();
      }else{
        ElMessage.error(response.data.msg);
      }
    })
  }
}

const dialogImageUrl = ref('')
const dialogImgVisible = ref(false)


const handleRemove = (uploadFile, uploadFiles) => {
  console.log(uploadFile, uploadFiles);
  let imgUrl = uploadFile.response.data;
  //2.给后端发请求,删除图片
  axios.post(BASE_URL+'/v1/file/remove?imgUrl='+imgUrl)
      .then((response)=>{
        if (response.data.code==2000){
          ElMessage.success('删除成功!');
        }
      })
}

/*const handlePictureCardPreview = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url
  dialogVisible.value = true
}*/
const isAddUserMode = ref(false);
</script>

<style scoped>

</style>